package cn.noodbabies.web.controller;

import cn.noodbabies.api.domain.LoginInfo;
import cn.noodbabies.api.domain.Note;
import cn.noodbabies.api.service.LoginInfoService;
import cn.noodbabies.api.service.NoteBaseService;
import cn.noodbabies.api.util.ResponseResult;
import cn.noodbabies.api.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private LoginInfoService loginInfoService;
    @Autowired
    private NoteBaseService noteBaseService;

    @RequestMapping("/")
    public String index(){
        /**
         * 安全退出
         *
         */
        if(null != UserContext.getLoginUser()){
            UserContext.setLoginUser(null);
        }
        return "redirect:/login.html";
    }

    @RequestMapping("/userLogin")
    @ResponseBody
    public ResponseResult userLogin(String username,String password){
        ResponseResult result = new ResponseResult();
        try {
            loginInfoService.checkLogin(username, password);
        }catch (Exception e){
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @RequestMapping("/main")
    public String main(Model model,HttpServletRequest request){
        LoginInfo loginUser = UserContext.getLoginUser();
        //如果是nologin则设置登录用户为其ip
        if (loginUser==null){
            loginUser = new LoginInfo();
            String remoteAddr = request.getRemoteAddr();
            loginUser.setUsername(remoteAddr);
            model.addAttribute("nologin",true);
        }
        model.addAttribute("loginfo",loginUser);
        //根据最新更新时间列出首页笔记
        List<Note> noteList = noteBaseService.indexListByNote();
        model.addAttribute("noteList",noteList);
        return "index";
    }

}
